from db_connection import DatabaseConnection
import sys
from datetime import datetime

# 数据库配置
SOURCE_DB_CONFIG = {
    'host': '172.24.222.53',
    'port': 3306,
    'user': 'report',
    'password': 'WjC#Ch&!WTUP9',
    'database': 'asd_lmdm_prd'
}

TARGET_DB_CONFIG = {
    'host': '172.24.222.13',
    'port': 3306,
    'user': 'root',
    'password': 'ES)Z+3AH&HUj',
    'database': 'asd_oms_prd'
}

def get_insert_sql(table_name, data):
    """生成INSERT SQL语句"""
    columns = list(data.keys())
    values = list(data.values())
    placeholders = ['%s'] * len(columns)
    
    sql = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({', '.join(placeholders)})"
    return sql, values

def sync_data(order_no):
    """同步指定订单号的数据"""
    source_db = DatabaseConnection(SOURCE_DB_CONFIG)
    target_db = DatabaseConnection(TARGET_DB_CONFIG)
    
    try:
        with source_db.cursor() as source_cursor, \
             target_db.cursor() as target_cursor, \
             target_db.transaction():
            
            # 1. 查询验证订单
            source_cursor.execute("""
                SELECT SERIAL_NUMBER, WORK_ORDER_NO 
                FROM eo_verification_order 
                WHERE ORDER_NO = %s
            """, (order_no,))
            verification_order = source_cursor.fetchone()
            
            if not verification_order:
                print(f"未找到验证订单: {order_no}")
                return
                
            serial_number = verification_order['SERIAL_NUMBER']
            work_order_no = verification_order['WORK_ORDER_NO']
            
            # 2. 根据SERIAL_NUMBER查询订单
            source_cursor.execute("""
                SELECT * FROM eo_t_order 
                WHERE EOOR_LOGISTIC_NO = %s 
                AND EOOR_ORDER_TYPE_CODE IN ('120', '180')
            """, (serial_number,))
            orders_120_180 = source_cursor.fetchall()
            
            # 3. 根据WORK_ORDER_NO查询订单
            source_cursor.execute("""
                SELECT * FROM eo_t_order 
                WHERE EOOR_WO_NO = %s 
                AND EOOR_ORDER_TYPE_CODE IN ('130')
            """, (work_order_no,))
            orders_130 = source_cursor.fetchall()
            
            # 处理所有订单
            all_orders = orders_120_180 + orders_130
            for order in all_orders:
                # 移除ID字段
                order_no = order['EOOR_ORDER_NO']
                order.pop('EOOR_ID', None)
                
                # 插入订单
                insert_sql, values = get_insert_sql('eo_t_order', order)
                target_cursor.execute(insert_sql, values)
                
                # 查询并插入订单明细
                source_cursor.execute("""
                    SELECT * FROM eo_t_order_item 
                    WHERE EOOI_ORDER_NO = %s
                """, (order_no,))
                order_items = source_cursor.fetchall()
                
                for item in order_items:
                    # 移除ID字段
                    item.pop('EOOI_ID', None)
                    insert_sql, values = get_insert_sql('eo_t_order_item', item)
                    target_cursor.execute(insert_sql, values)
            
            print(f"成功同步订单 {order_no} 的数据")
            
    except Exception as e:
        print(f"同步数据时出错: {str(e)}")
        raise
        
    finally:
        source_db.close()
        target_db.close()

def main():
    if len(sys.argv) != 2:
        print("使用方法: python data_sync.py <ORDER_NO>")
        sys.exit(1)
        
    order_no = sys.argv[1]
    sync_data(order_no)

if __name__ == "__main__":
    main() 